#include "Topic.h"

#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>

#include "recovery/fs/Path.h"
#include "recovery/fs/file/File.h"


using recovery::Status;

using recovery::fs::file::File;

Topic::Topic(const std::string & name, const std::string & root)
: _root(root)
, _directory(recovery::fs::Path::from(root, name))
, _logPath(recovery::fs::Path::from(_directory, name + ".log"))
, _metaPath(recovery::fs::Path::from(_directory, name + ".meta"))
{
}
int Topic::open() {
	if(!isOpened()){
		const std::lock_guard<std::mutex> lock(mutex);

		if(!createDirIfNotExist(_directory)){
			return -1;
		}

		_opened = true; 
	}
	return 0;
};
int Topic::close(){
	if(isOpened()){
		const std::lock_guard<std::mutex> lock(mutex);

		//TODO: flush filesystem
		//TODO: close fs resource
		_opened = false;
	}
	return 0;
}

Status Topic::createDirIfNotExist(const std::string & dir){
	//TODO: create parent directory for dir
	if(mkdir(dir.c_str(), 0755) != 0){//create failed
		if(errno != EEXIST){
			std::cout << "create failed, and not exist dir, errno:" << errno << ":" << strerror(errno) << std::endl;
			return Status::Failed("create data directory failed");
		}
		else{
			std::cout << "directory:[" << _directory << "]: is exist already" << std::endl;
		}
	}
	else{
		// isDir(
		std::cout << "create directory:[" << _directory << "]:OK" << std::endl;
	}
	return Status::OK();
}
